package vn.orderonline.core.dao;

import java.sql.Time;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import vn.orderonline.core.commons.utils.StringUtils;
import vn.orderonline.core.dao.common.GenericDaoImpl;
import vn.orderonline.core.dao.entity.Restaurant;

@Repository
public class RestaurantDaoImpl extends GenericDaoImpl<Restaurant, Integer>
		implements RestaurantDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<Restaurant> search(String restaurantName,
			String restaurantTitle, String restaurantAddress, String openTime,
			String closeTime, Float deliveryPrice, Float minimumBill) {
		Criteria criteria = getSession().createCriteria(Restaurant.class);
		if (!StringUtils.isNullOrEmpty(restaurantName)) {
			criteria.add(Restrictions.like("restaurantName", "%"
					+ restaurantName + "%"));
		}
		if (!StringUtils.isNullOrEmpty(restaurantTitle)) {
			criteria.add(Restrictions.like("restaurantTitle", "%"
					+ restaurantTitle + "%"));
		}
		if (!StringUtils.isNullOrEmpty(restaurantAddress)) {
			criteria.add(Restrictions.like("restaurantAddress", "%"
					+ restaurantAddress + "%"));
		}
		if (!StringUtils.isEmpty(openTime)) {
			criteria.add(Restrictions.eq("openTime",
					Time.valueOf(openTime + ":00")));
		}
		if (!StringUtils.isEmpty(closeTime)) {
			criteria.add(Restrictions.eq("closeTime",
					Time.valueOf(closeTime + ":00")));
		}
		if (!StringUtils.isEmpty(deliveryPrice)) {
			criteria.add(Restrictions.eq("deliveryPrice", deliveryPrice));
		}
		if (!StringUtils.isEmpty(minimumBill)) {
			criteria.add(Restrictions.eq("minOrder", minimumBill));
		}
		return criteria.list();
	}

	@Override
	public Boolean checkExistedRestaurant(String restaurantName) {
		Criteria criteria = getSession().createCriteria(Restaurant.class);
		criteria.add(Restrictions.eq("restaurantName", restaurantName));
		return (criteria.uniqueResult() != null) ? true : false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> getAllRestaurantIdAndName() {
		Criteria criteria = getSession().createCriteria(Restaurant.class);
		criteria.setProjection(Projections.projectionList()
				.add(Projections.property("restaurantId"))
				.add(Projections.property("restaurantName")));
		List<Object[]> list = criteria.list();
		Map<String, String> map = new HashMap<>();
		for (Object[] obj : list) {
			map.put(obj[0].toString(), obj[1].toString());
		}
		return map;
	}

}
